package arithmetic;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: javaLearn
 * @description: 力扣两数之和
 * @author: renhai
 * @Date ：2022/3/10 21:30
 **/

public class sumOfNums {

    /**
     * @Description: 两数之和暴力枚举
     * @return:
     * @Author: renhai
     * @Date: 2022/3/10
     */
    public int[] twoSum1(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    /**
     * @param null
     * @Description: 哈希表实现两数之和
     * @return:
     * @Author: renhai
     * @Date: 2022/3/10
     */
    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }

}
